<?php
/**
 * crcl/base
 *
 * Copyright 2013 CRCL - André Sabosch - info@crcl.de
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace crcl\base\i18n;

interface ITranslator
{
  public static function prepare($sUri);

  public static function setLanguages($sLanguage);
  public static function getLanguage();

  public static function translate($sKey, $sGroup);
}

class Translator implements ITranslator
{
  public static function prepare($sUri)
  {
    $sTheme = 'default';
    if (\crcl\base\Mvc::hasTheme())
    {
      $sTheme = \crcl\base\Mvc::getTheme();
    }

    $sDirectory = \crcl\base\application\Path::getDirectory(\crcl\base\application\Path::DIR_I18N);
    $sDirectory .= $sTheme . '/';

    self::$sUri = $sUri . $sDirectory;
  }

  public static function setLanguages($sLanguage)
  {
    self::$aLanguages = func_get_args();
  }

  public static function getLanguage()
  {
    return self::$aLanguages[0];
  }

  public static function translate($sKey, $sGroup)
  {
    foreach (self::$aLanguages as $sLanguage)
    {
      $sUri = self::$sUri . $sLanguage . '.ini'; //todo this just works on ini config uris

      try
      {
        $sOutput = \crcl\base\Config::getInstance($sUri)->get($sGroup, $sKey);

        return $sOutput;
      }
      catch (\crcl\base\config\reader\Exception $e)
      {
        //do nothing: just continue foreach
      }
    }
    throw new Exception('Translation not found.', Exception::ERROR_TRANSLATION_NOTFOUND,
        array('key' => $sKey, 'group' => $sGroup, 'uri' => $sUri));
  }

  private static $sUri;
  private static $aLanguages = array('en_GB');
}